package com.listen.playanddown;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.listen.playanddown.bean.ChangeNotifi;
import com.listen.playanddown.bean.MusicBean;
import com.listen.playanddown.bean.PercentBean;
import com.listen.playanddown.bean.PlayClick;
import com.listen.playanddown.service.MusicService;
import com.wgl.android.library.base.BaseActivity;

import butterknife.Bind;
import butterknife.OnClick;
import rx.functions.Action1;

public class PlayActivity extends BaseActivity {
    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.startNum)
    TextView startNum;
    @Bind(R.id.endNum)
    TextView endNum;
    @Bind(R.id.seekBar)
    SeekBar seekBar;
    @Bind(R.id.img)
    ImageView img;
    @Bind(R.id.bei)
    Button beiNum;

    @Override
    public int getLayoutId() {
        return R.layout.activity_play;
    }

    @Override
    protected void initView() {
        initDate();
        initService();
        //接收service发送的音乐播放准备完成消息，更新界面
        mRxManager.on("updatePage", new Action1<MusicBean.MsgEntity.DataEntity>() {
            @Override
            public void call(MusicBean.MsgEntity.DataEntity music) {
                if (music != null) {
                    stopProgressDialog();
                    if (Build.VERSION.SDK_INT >= 23) {
                        try {
                            iMusic.setPlaySpeed(bei);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                    Glide.with(PlayActivity.this).load(music.getThumbnail()).into(img);
                    name.setText("" + music.getTitle());
                    endNum.setText("" + music.getMp3_duration());
                    Log.e("---", "准备好啦" + music.getMp3_duration());
                    String[] split = music.getMp3_duration().split(":");
                    int a = Integer.parseInt(split[1]) * 60 + Integer.parseInt(split[2]);
                    seekBar.setMax(a * 1000);
                    handler.sendEmptyMessage(PROGRESS);
                }

            }
        });
        //seekbar的拖动事件
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //拖动
                if (fromUser) {
                    try {
                        iMusic.seekTo(progress);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        mRxManager.on("percent", new Action1<PercentBean>() {
            @Override
            public void call(PercentBean percentBean) {
                seekBar.setSecondaryProgress((int) (seekBar.getMax() * percentBean.getPercent() / 100));
            }
        });
        mRxManager.on("notifi", new Action1<PlayClick>() {
            @Override
            public void call(PlayClick playClick) {
                Log.e("-----playClick2", "===" + playClick.getI());
                if (playClick.getI() == 0) {
                    try {
                        if (iMusic.isPlaying()) {
                            play.setImageResource(R.drawable.notify_btn_dark_play_normal);
                        } else {
                            play.setImageResource(R.drawable.notify_btn_dark_pause_normal);
                        }

                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                } else {
                }
            }
        });


    }


    private void initService() {
        Intent intent = new Intent(this, MusicService.class);
        intent.setAction("com.jm.music");
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
        startService(intent);
    }

    @Bind(R.id.play)
    ImageView play;


    @OnClick({R.id.pre, R.id.play, R.id.next, R.id.go_left, R.id.go_right, R.id.bei})
    public void click(View view) {
        switch (view.getId()) {
            //上一首
            case R.id.pre:
                if (!NoFastClickUtils.isFastClick()) {
                    try {
                        iMusic.playTop();
                        play.setImageResource(R.drawable.notify_btn_dark_pause_normal);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.play:
                playClick();
                break;
            //下一首
            case R.id.next:

                if (!NoFastClickUtils.isFastClick()) {
                    try {
                        iMusic.playNext();
                        play.setImageResource(R.drawable.notify_btn_dark_pause_normal);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }

                break;
            case R.id.go_left:
                try {
                    iMusic.seekTo(Integer.parseInt(iMusic.getProgress()) - 15 * 1000);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.go_right:
                try {
                    iMusic.seekTo(Integer.parseInt(iMusic.getProgress()) + 15 * 1000);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.bei:


                if (Build.VERSION.SDK_INT >= 23) {
                    if (bei == 1) {
                        bei = 1.5;
                    } else if (bei == 1.5) {
                        bei = 2;
                    } else if (bei == 2) {
                        bei = 2.5;
                    } else if (bei == 2.5) {
                        bei = 3;
                    } else if (bei == 3) {
                        bei = 1;
                    }
                    beiNum.setText(bei + "");
                    try {
                        iMusic.setPlaySpeed(bei);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                } else {
                    showShortToast("仅支持6.0+");
                }

        }

    }

    double bei = 1;

    //播放暂停（页面和通知栏的点击）
    private void playClick() {
        try {
            if (iMusic.isPlaying()) {
                play.setImageResource(R.drawable.notify_btn_dark_play_normal);
                iMusic.puaseMusic();
                mRxManager.post("changeNotifi", new ChangeNotifi(0));
            } else {
                play.setImageResource(R.drawable.notify_btn_dark_pause_normal);
                iMusic.playMusic();
                mRxManager.post("changeNotifi", new ChangeNotifi(1));
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    //绑定服务
    private IMusicService iMusic;

    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName n, IBinder service) {
            iMusic = IMusicService.Stub.asInterface(service);
            if (iMusic != null) {
                try {
                    //获取当前播放的position和点击的position
                    Log.e("---", "链接成功" + iMusic.getCurrentPosition() + "\\" + position);
                    if (iMusic.getCurrentPosition() != position) {
                        startProgressDialog();
                    }
                    try {

                        mRxManager.post("changeNotifi", new ChangeNotifi(1));
                        //  当前播放的position==在播放的，则不重新播放，
                        if (iMusic.getCurrentPosition() == position) {
                            Glide.with(PlayActivity.this).load(iMusic.getImageUrl()).into(img);
                            name.setText("" + iMusic.getName());
                            endNum.setText("" + iMusic.getTime());
                            String[] split = iMusic.getTime().split(":");
                            int a = Integer.parseInt(split[1]) * 60 + Integer.parseInt(split[2]);
                            seekBar.setMax(a * 1000);
                            handler.sendEmptyMessage(PROGRESS);
                        } else
                            iMusic.openMusic(position);
                    } catch (NullPointerException e) {
                        // iMusic.openMusic(position);
                        Intent intent = new Intent(PlayActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    }


                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    private static final int PROGRESS = 1;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case PROGRESS:
                    try {
//                        //1.得到当前进度
                        int position = Integer.parseInt("".equals(iMusic.getProgress()) ? "0" : iMusic.getProgress());
//                        Log.e("position", position + "");

                        //2、设置seekbar的进度
                        seekBar.setProgress(position);
                        //  Log.e("position", position + "-" + iMusic.getSecondaryProgress() + "-" + seekBar.getMax());
                        //  seekBar.setSecondaryProgress(iMusic.getSecondaryProgress());
                        //3时间进度更新
                        startNum.setText(utils.stringForTime(position));
                        //4 ，每秒进一次、
                        handler.removeMessages(PROGRESS);
                        handler.sendEmptyMessageDelayed(PROGRESS, 1000);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        if (conn != null)
            unbindService(conn);

        super.onDestroy();
    }

    private int position;
    private Utils utils;

    private void initDate() {
        position = getIntent().getIntExtra("position", 0);
        utils = new Utils();
    }
}
